package logic

import (
	"context"
	"encoding/json"
	"home-lister/model/cache"
	"home-lister/model/mysql"
	"time"

	"home-lister/homerpc/homerpc"
	"home-lister/homerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type HomeListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHomeListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HomeListLogic {
	return &HomeListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *HomeListLogic) HomeList(in *homerpc.HomeListRequest) (*homerpc.HomeListResponse, error) {
	// todo: add your logic here and delete this line

	var homes []mysql.Home

	result, _ := cache.Rdb.Get(l.ctx, "homeList").Result()
	if result == "" {
		mysql.DB.Debug().Find(&homes)
		jsonData, _ := json.Marshal(homes)
		cache.Rdb.Set(l.ctx, "homeList", jsonData, time.Minute*3)
	} else {
		json.Unmarshal([]byte(result), &homes)
	}

	var homeList []*homerpc.HomeList

	for _, home := range homes {
		list := homerpc.HomeList{
			HomeId:  int64(home.ID),
			Name:    home.Name,
			Price:   float32(home.Price),
			Address: home.Address,
		}
		homeList = append(homeList, &list)
	}

	return &homerpc.HomeListResponse{
		List: homeList,
	}, nil
}
